import { defineStore } from 'pinia'

import '@kitware/vtk.js/Rendering/Profiles/Geometry';

import vtkFullScreenRenderWindow from '@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow';
import vtkScalarBarActor from '@kitware/vtk.js/Rendering/Core/ScalarBarActor';

import vtkAxesActor from '@kitware/vtk.js/Rendering/Core/AxesActor';
import vtkOrientationMarkerWidget from '@kitware/vtk.js/Interaction/Widgets/OrientationMarkerWidget';

import { getVtkReaderOrKeyValue } from "../../utils/vtk/vtkReaderList.js";

import vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper";
import vtkActor from "@kitware/vtk.js/Rendering/Core/Actor";

import vtkHttpDataAccessHelper from '@kitware/vtk.js/IO/Core/DataAccessHelper/HttpDataAccessHelper';
import vtkITKPolyDataReader from '@kitware/vtk.js/IO/Misc/ITKPolyDataReader';
import readPolyDataArrayBuffer from 'itk/readPolyDataArrayBuffer';

import vtkInterActorStyleManipulator from "@kitware/vtk.js/Interaction/Style/InteractorStyleManipulator";
import { keyboardCombination, manipulatorFactory } from "../../utils/vtk/customActionBars.js";
import Config from 'paraview-glance/fastCAE/config';
import vtkProxyManager from '@kitware/vtk.js/Proxy/Core/ProxyManager';
import vtkGestureCameraManipulator from "@kitware/vtk.js/Interaction/Manipulators/GestureCameraManipulator";
console.log('Config',Config)
vtkITKPolyDataReader.setReadPolyDataArrayBufferFromITK(readPolyDataArrayBuffer);
import {
  DEFAULT_VIEW_ORIENTATION,
} from '../../utils/constants.js';
import {
  updateViewOrientationFromBasisAndAxis,
} from '../../utils/utils.js';
export const viewsModule = defineStore('VIEWS', {
  state () {
    return {
      vtkReaderObj: getVtkReaderOrKeyValue(),
      renderer: null,
      renderWindow: null,
      scalarBarActor: null,
      screenRender: null,
      actor: null,
      mapper: null,
      interActorStyle: vtkInterActorStyleManipulator.newInstance(),
      customActionBars: {
        keyboardCombination,
        manipulatorFactory
      },
      currentColorList: [],
      source: null,
      view: null,
      proxyManager: null,
      viewOrientation: DEFAULT_VIEW_ORIENTATION,
      loadingModel: true,
      loadingIsOk: true,
      modelActorArr: [],//模型的数据数组
    }
  },
  actions: {
    // 初始化cnavas画布
    initViews (container) {
      const proxyConfiguration = Config.Proxy
      this.proxyManager = vtkProxyManager.newInstance({ proxyConfiguration });
      this.view = this.proxyManager.createProxy('Views', 'View3D', {
        name: 'default'
      })
      this.view.setContainer(container);
      this.view.setOrientationAxesVisibility(true);
      this.view.setBackground(0.6, 0.6, 0.6);
      setTimeout(() => {
        this.view.resize()
      }, 0);
      this.renderer = this.view.getRenderer();
      this.renderWindow = this.view.getRenderWindow()
      window.addEventListener('resize', () => {
        this.view.resize()
      })
      this.updateViewOrientationFromBasisAndAxisFn();
    },
    // 加载file文件
    loadFile (files) {
      for (let i = 0; i < files.length; i++) {
        this.readFile(files.item(i));
      }
    },
    // 读取file文件
    readFile (file) {
      const readerMapping = this.getReader(file);
      if (readerMapping) {
        const { readMethod } = readerMapping;
        const io = new FileReader();
        const that = this
        io.onload = function onLoad () {
          that.readRawData(file.name, io.result, readerMapping)
        }
        io[readMethod](file);
      } else {
        console.log('No reader mapping')
      }
    },
    // 通过file加载模型
    getReader ({ name }) {
      const lowerCaseName = name.toLowerCase();
      // 匹配映射器
      const extToUse = Object.keys(this.vtkReaderObj).find((ext) => {
        return lowerCaseName.endsWith(ext);
      });
      return this.vtkReaderObj[extToUse];
    },
    // 加载模型
    readRawData (fileName, data, readerMapping, resolve = null, reject = null) {
      // return new Promise((resolve, reject) => {
      const { vtkReader, parseMethod, fileNameMethod } = readerMapping;
      const reader = vtkReader.newInstance()
      this.loadingModel = true
      if (fileNameMethod) {
        // 匹配相关的映射器做处理
        reader[fileNameMethod](fileName);
      }
      try {
        const ds = reader[parseMethod](data);
        //return
        Promise.resolve(ds).then((dataset) => {
           console.log('dataset', ds);
          // 创建图形数据
          const mapper = vtkMapper.newInstance({
            interpolateScalarsBeforeMapping: false,
            useLookupTableScalarRange: true,
            scalarVisibility: false,
          });

          const source = reader.getOutputData();
          console.log('source', source);
          const currentColorList =  source.getPointData().getArrays().map((color) => ({
            label: `${color.getName()}`,
            value: `PointData:${color.getName()}`,
          }))
          // vtkActor用于表示渲染场景中的实体(mapper) 主要设置模型的位置以及方向相关的功能
          const actor = vtkActor.newInstance();
          // 将模型传输到可视化管道
          actor.setMapper(mapper);
          // 指定一个数据对象作为输入。
          mapper.setInputData(source);
          // 添加到渲染器中
          this.renderer.addActor(actor);
          // this.scalarBarActor.setScalarsToColors(this.mapper.getLookupTable());// 添加标量栏
          // 重置相机
          this.renderer.resetCamera();
          this.renderWindow.render();
          this.updateViewOrientationFromBasisAndAxisFn();
          this.pushModelActorArr(mapper, source, actor, currentColorList, fileName)
          resolve && resolve('模型加载成功')
        }).catch((err) => {
          // this.setLoadingIsOk(false)
          // this.setLoadingModel(false)
          console.log('模型加载失败');
          reject && reject('模型加载失败')
        })
      } catch (e) {
        reject && reject('模型数据加载报错')
      }
      // })

    },
     // 将模型存起来
     pushModelActorArr(mapper, source, actor, currentColorList, name) {
      const objInfo = {
        mapper, source, actor, currentColorList, currentModelShowHidden: true, name,
        currentColor: '',
        modelColor: '',
        currentRepresentation: '',
        backgroundColorList: [
          '#9e0142',
          '#d53e4f',
          '#fdae61',
          '#409EFF',
          '#abdda4',
          '#a5a7c5',
          '#394664',
        ],
      };
      this.modelActorArr.push(objInfo)
    },
    //重置单个模型数据
    initModelInfo (index) {
      this.modelActorArr[index].currentColor = ''
      this.modelActorArr[index].modelColor = ''
      this.modelActorArr[index].currentRepresentation = '1:2:0'
    },
    // 重置模型数组
    initModelActorArr () {
      this.modelActorArr = []
    },
    //显示隐藏模型
    showHiddenModel(value, index) {
      this.modelActorArr[index].currentModelShowHidden = value
    },
    getCenterOfScene () {
      const bounds = this.renderer.computeVisiblePropBounds();
      const center = [0, 0, 0];
      center[0] = (bounds[0] + bounds[1]) / 2.0;
      center[1] = (bounds[2] + bounds[3]) / 2.0;
      center[2] = (bounds[4] + bounds[5]) / 2.0;
      return center;
    },
    settingKeyboardCombination () {
      this.interActorStyle.removeAllMouseManipulators();
      Object.keys(this.customActionBars.keyboardCombination).forEach(name => {
        const fun = manipulatorFactory[this.customActionBars.keyboardCombination[name].handle];
        if (fun) {
          const manipulator = fun.newInstance();
          manipulator.setButton(this.customActionBars.keyboardCombination[name].button);
          manipulator.setShift(!!this.customActionBars.keyboardCombination[name].shift);
          manipulator.setControl(!!this.customActionBars.keyboardCombination[name].control);
          manipulator.setAlt(!!this.customActionBars.keyboardCombination[name].alt);
          if (this.customActionBars.keyboardCombination[name].scrollEnabled !== undefined) {
            manipulator.setScrollEnabled(this.customActionBars.keyboardCombination[name].scrollEnabled);
          }
          if (this.customActionBars.keyboardCombination[name].dragEnabled !== undefined) {
            manipulator.setDragEnabled(this.customActionBars.keyboardCombination[name].dragEnabled);
          }
          this.interActorStyle.addMouseManipulator(manipulator);
        }
      })
      this.interActorStyle.addGestureManipulator(vtkGestureCameraManipulator.newInstance());
    },
    // 通过url获取加载所需要的renderer
    getReaderByUrl (nameByUrl) {
      const extToUse = Object.keys(this.vtkReaderObj).find((ext) => {
        return nameByUrl.endsWith(ext);
      });
      return this.vtkReaderObj[extToUse];
    },
    // 通过url加载模型
    urlLoadData (url) {
      // console.log('url', url);
      return new Promise((resolve, reject) => {
        const parts = url.split('/');
        const nameByUrl = parts[parts.length - 1];
        const readerMapping = this.getReaderByUrl(nameByUrl);
        if (readerMapping) {
          vtkHttpDataAccessHelper.fetchBinary(url, {}).then((data) => {
            this.readRawData(nameByUrl, data, readerMapping, resolve, reject);
          }).catch((err) => {
            // this.setLoadingIsOk(false)
            // this.setLoadingModel(false)
            console.log('模型加载失败');
            reject('模型加载失败')
          })
        } else {
          // this.setLoadingIsOk(false)
          // this.setLoadingModel(false)
          reject('没有找到对应的reader')
        }
      })

    },
    // 初始化纠正相机
    updateViewOrientationFromBasisAndAxisFn () {
      updateViewOrientationFromBasisAndAxis(
        this.view,
        this.viewOrientation,
        'default'
      );
    },
    // 删除所有数据，canvas，actor，mapper
    unmountView () {
      this.view.setContainer(null);
      this.view = null
      console.log('清空视图');
    },
    // 设置模型加载loading
    setLoadingModel (value) {
      this.loadingModel = value
    },
    // 设置模型加载失败或成功
    setLoadingIsOk (value) {
      this.loadingIsOk = value
    },
    // 删除单个模型数据
    deleteModelActorArr(index) {
      this.modelActorArr.splice(index, 1)
    },
    // 删除所有数据，canvas，actor，mapper
    unmountView(view) {
      this.view.setContainer(null);
      this.view = null
    },
  }
})